<template>
  <div class="login">
    <div class="login-box">
      <p>后台管理系统</p>
      <el-form
        label-width="80px"
        :rules="rules"
        class="login-from"
        :model="loginform"
        ref="loginRef"
        :hide-required-asterisk="hide"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="loginform.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码：" prop="password">
          <el-input v-model="loginform.password" type="password"></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btn">
          <el-button type="primary" @click="login">登陆</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      hide: true,
      //登陆数据保护
      loginform: {
        username: "admin",
        password: "123456",
      },
      //表单验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入登陆密码", trigger: "blur" },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    login() {
      this.$refs.loginRef.validate(async (valid) => {
        // this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.post("login", this.loginform);
        if (res.meta.status !== 200) return this.$message.error("登录失败");
        this.$message.success("登录成功");
        // 1、将登陆成功之后的token, 保存到客户端的sessionStorage中; localStorage中是持久化的保存
        //   1.1 项目中出现了登录之外的其他API接口，必须在登陆之后才能访问
        //   1.2 token 只应在当前网站打开期间生效，所以将token保存在sessionStorage中
        window.sessionStorage.setItem("token", res.data.token);
        // 2、通过编程式导航跳转到后台主页, 路由地址为：/home
        this.$router.push("/home");
      });
    },

    reset() {
      this.$refs.loginRef.resetFields();
    },
  },
};
</script>

<style scoped>
.login {
  background-color: #2b4b6b;
  height: 100%;
  position: relative;
}
p {
  text-align: center;
  margin-top: 30px;
  font-size: 23px;
}
.login-box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 5px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.btn {
  display: flex;
  justify-content: center;
}
.login-from {
  position: absolute;
  top: 100px;
  left: 10px;
  right: 30px;
}
</style>
